<template>
  <div class="admin-layout">
    <!-- 侧边栏 -->
    <el-aside width="220px" class="aside">
      <div class="logo">
        <img src="@/assets/jiang.jpg" alt="Logo">
        <span>后台管理系统</span>
      </div>
      
      <!-- 添加菜单组件 -->
      <el-menu
        :default-active="activeMenuPath"
        class="menu"
        :collapse="isCollapse"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        router
      >
        <template v-for="(routes, group) in menuGroups" :key="group">
          <el-sub-menu v-if="routes.length > 1" :index="group">
            <template #title>
              <el-icon><component :is="routes[0].meta?.icon || 'Menu'" /></el-icon>
              <span>{{ group }}</span>
            </template>
            <el-menu-item 
              v-for="route in routes" 
              :key="route.path"
              :index="'/jiang/' + route.path"
            >
              <el-icon><component :is="route.meta?.icon || 'Menu'" /></el-icon>
              <span>{{ route.meta?.title }}</span>
            </el-menu-item>
          </el-sub-menu>
          <el-menu-item 
            v-else 
            :index="'/jiang/' + routes[0].path"
          >
            <el-icon><component :is="routes[0].meta?.icon || 'Menu'" /></el-icon>
            <span>{{ routes[0].meta?.title }}</span>
          </el-menu-item>
        </template>
      </el-menu>
    </el-aside>

    <!-- 主要内容区域 -->
    <el-container class="main-container">
      <!-- 顶部导航栏 -->
      <el-header class="header">
        <div class="header-left">
          <el-icon 
            class="collapse-btn"
            @click="toggleCollapse"
          >
            <Fold v-if="!isCollapse" />
            <Expand v-else />
          </el-icon>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/jiang/dashboard' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>{{ currentRouteText }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <el-dropdown trigger="click" @command="handleCommand">
            <div class="user-info">
              <el-avatar :size="32" :src="userInfo.icon" />
              <span class="username">{{ userInfo.nickName }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="password">修改密码</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 内容区域 -->
      <el-main class="main">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { useAdminStore } from '@/stores/modules/admin'
import { 
  Fold, 
  Expand, 
  Monitor,
  Goods,
  List,
  User,
  Grid,
  Setting,
  Menu,
  UserFilled,
  Lock,
  ShoppingCart
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const adminStore = useAdminStore()

// 侧边栏折叠状态
const isCollapse = ref(false)
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 当前激活的菜单路径
const activeMenuPath = computed(() => {
  return route.path;
});

// 当前路由的面包屑文本
const currentRouteText = computed(() => {
  // 优先使用 meta.title，如果不存在则使用路由 name，再不存在则使用 path
  return route.meta.title || route.name || route.path;
});

// 用户信息
const userInfo = computed(() => ({
  nickName: adminStore.adminInfo?.nickName || '管理员',
  icon: adminStore.adminInfo?.icon || ''
}))

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      // TODO: 跳转到个人信息页面或显示个人信息弹窗
      console.log('跳转到个人信息')
      ElMessage.info('即将跳转到个人信息页面')
      // router.push('/jiang/profile') // 假设有个人信息路由
      break
    case 'password':
      // TODO: 跳转到修改密码页面或显示修改密码弹窗
      console.log('跳转到修改密码')
      ElMessage.info('即将跳转到修改密码页面')
      // router.push('/jiang/change-password') // 假设有修改密码路由
      break
    case 'logout':
      ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await adminStore.logout()
        router.push('/jiang/adminLogin')
      }).catch(() => {
        // 用户取消操作
      })
      break
  }
}

// 获取后台 children 路由
const jiangRoute = router.options.routes.find(r => r.path === '/jiang')
const adminRoutes = jiangRoute
  ? jiangRoute.children.filter(r => r.meta && r.meta.title && r.meta.showInMenu !== false)
  : []

// 分组
const menuGroups = computed(() => {
  const groups = {}
  adminRoutes.forEach(r => {
    const group = r.meta.group || '其它'
    if (!groups[group]) groups[group] = []
    groups[group].push(r)
  })
  return groups
})

const iconMap = { Goods, List, User, Grid, Setting, Monitor, UserFilled, Lock, ShoppingCart }
</script>

<style lang="scss" scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  background-color: #f0f2f5;

  .aside {
    background-color: #304156;
    transition: width 0.3s;
    overflow-x: hidden;

    .logo {
      height: 60px;
      display: flex;
      align-items: center;
      padding: 0 20px;
      background-color: #2b3649;
      
      img {
        width: 32px;
        height: 32px;
        margin-right: 12px;
      }
      
      span {
        color: #fff;
        font-size: 16px;
        font-weight: 600;
        white-space: nowrap;
      }
    }

    .menu {
      border-right: none;
    }
  }

  .main-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .header {
      background-color: #fff;
      border-bottom: 1px solid #e6e6e6;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      height: 60px;

      .header-left {
        display: flex;
        align-items: center;
        gap: 20px;

        .collapse-btn {
          font-size: 20px;
          cursor: pointer;
          color: #606266;
          
          &:hover {
            color: var(--primary-color);
          }
        }
      }

      .header-right {
        .user-info {
          display: flex;
          align-items: center;
          gap: 8px;
          cursor: pointer;
          padding: 4px 8px;
          border-radius: 4px;
          transition: background-color 0.3s;

          &:hover {
            background-color: #f5f7fa;
          }

          .username {
            color: #606266;
          }
        }
      }
    }

    .main {
      padding: 20px;
      overflow-y: auto;
    }
  }
}

// 路由切换动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
